package io.renren.modules.sys.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import io.renren.common.utils.*;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.sys.entity.SupplierEntity;
import io.renren.modules.sys.service.SupplierService;
import io.renren.modules.sys.service.UserBusinessService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 供应商/客户信息表
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2018-11-22 14:29:36
 */

@RestController
@RequestMapping("sys/supplier")
public class SupplierController {
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private UserBusinessService userBusinessService;

    /**
     * 查找客户信息
     * condition.put("type_s_like", "供应商");
     * condition.put("enabled_s_eq", 1);
     * condition.put("id_s_order", "desc");
     */
    @RequestMapping("/findBySelect_cus")
    public R findBySelect_cus(@RequestParam Map<String, Object> params) {
        params.put("page", "0");
        params.put("limit", "10");
        params.put("type", "客户");
        params.put("enabled", "1");
        params.put("order", "desc");

        PageUtils page = supplierService.querySuppliers(params);

        List<?> dataList = page.getList();
        JSONArray dataArray = new JSONArray();
        for (int i = 0; i < dataList.size(); i++) {
            JSONObject item = new JSONObject();
            SupplierEntity supplier = (SupplierEntity) dataList.get(i);
            Boolean flag = false;
            Map<String, Object> temp = new HashMap();
            temp.put("Type", params.get("UBType") == null ? "" : params.get("UBType"));
            temp.put("KeyId", params.get("UBKeyId") == null ? "" : params.get("UBKeyId"));
            temp.put("Value", "[" + supplier.getId().toString() + "]");
            flag = userBusinessService.checkIsUserBusinessExist(temp);
            if (flag == true) {
                item.put("id", supplier.getId()); // 客户id
                item.put("supplier", supplier.getSupplier()); //客户名称
                dataArray.add(item);
            }
        }

        return R.ok().put("data", dataArray);
    }

    @RequestMapping("/findBySelect_cust")
    public JSONArray findBySelect_cust(@RequestParam Map<String, Object> params) {
        params.put("type", "客户");
        params.put("enabled", "1");
        params.put("order", "desc");

        PageUtils page = supplierService.querySuppliers(params);

        List<?> retList = page.getList();
        JSONArray dataArray = new JSONArray();
        for (int i = 0; i < retList.size(); i++) {
            Boolean flag = false;
            JSONObject item = new JSONObject();
            SupplierEntity supplier = (SupplierEntity) retList.get(i);
            Map<String, Object> temp = new HashMap();
            temp.put("Type", params.get("UBType") == null ? "" : params.get("UBType"));
            temp.put("KeyId", params.get("UBKeyId") == null ? "" : params.get("UBKeyId"));
            temp.put("Value", "[" + supplier.getId().toString() + "]");
            flag = userBusinessService.checkIsUserBusinessExist(temp);
            if (flag == true) {
                item.put("id", supplier.getId());
                item.put("supplier", supplier.getSupplier());
                dataArray.add(item);
            }
        }

        return dataArray;
    }

    /**
     * 查找客户信息
     * condition.put("type_s_like", "供应商");
     * condition.put("enabled_s_eq", 1);
     * condition.put("id_s_order", "desc");
     */
    @RequestMapping("/findBySelect_sup")
    public JSONArray findBySelect_sup() {
        Map<String, Object> params = new HashMap<>();
        params.put("type", "供应商");
        params.put("enabled", "1");
        params.put("order", "desc");
        PageUtils page = supplierService.querySuppliers(params);

        List<?> dataList = page.getList();
        JSONArray dataArray = new JSONArray();
        for (int i = 0; i < dataList.size(); i++) {
            JSONObject item = new JSONObject();
            SupplierEntity supplier = (SupplierEntity) dataList.get(i);
            item.put("id", supplier.getId());
            item.put("supplier", supplier.getSupplier()); //客户名称
            dataArray.add(item);
        }

        return dataArray;
    }

    /**
     * 查找会员信息-下拉框
     * condition.put("type_s_like", "会员");
     * condition.put("enabled_s_eq", 1);
     * condition.put("id_s_order", "desc");
     *
     * @return
     */
    @RequestMapping("/findBySelect_retail")
    public JSONArray findBySelect_retail() {
        Map<String, Object> params = new HashMap<>();
        params.put("type", "会员");
        params.put("enabled", "1");
        params.put("order", "desc");
        PageUtils page = supplierService.findBySelect_retail(params);
        List<?> dataList = page.getList();
        //存放数据json数组
        JSONArray dataArray = new JSONArray();
        if (null != dataList) {
            for (int i = 0; i < dataList.size(); i++) {
                JSONObject item = new JSONObject();
                SupplierEntity supplier = (SupplierEntity) dataList.get(i);
                item.put("id", supplier.getId());
                //客户名称
                item.put("supplier", supplier.getSupplier());
                item.put("advanceIn", supplier.getAdvancein()); //预付款金额
                dataArray.add(item);
            }
        }

        return dataArray;
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:supplier:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = supplierService.queryPage(params);

        return R.ok().put("page", page);
    }

    @RequestMapping("/findBy")
    public R findBy(@RequestParam Map<String, Object> params) {
        String pageSize = "15";
        String pageNo = "1";
        Object pageSizeObj = params.get("pageSize");
        Object pageNoObj = params.get("pageNo");
        if (pageSizeObj != null) {
            pageSize = pageSizeObj.toString();
        }
        if (pageNoObj != null) {
            pageNo = pageNoObj.toString();
        }
        params.put("limit", pageSize);
        params.put("page", pageNo);
        Page<SupplierEntity> page = supplierService.selectPage(
                new Query<SupplierEntity>(params).getPage(),
                new EntityWrapper<SupplierEntity>()
                        .like("type", Tools.dealNullStr(params.get("type")))
                        .like("supplier", Tools.dealNullStr(params.get("supplier")))
                        .like("phonenum", Tools.dealNullStr(params.get("phonenum")))
                        .like("telephone", Tools.dealNullStr(params.get("telephone")))
                        .like("description", Tools.dealNullStr(params.get("description")))
        );

        PageUtils pageUtils = new PageUtils(page);

        return R.ok().put("total", pageUtils.getTotalCount()).put("rows", pageUtils.getList());
    }

    /**
     * 更新会员的预收款信息
     * SupplierID: 45
     * AdvanceIn: 222.00
     */
    @RequestMapping("/updateAdvanceIn")
    public R updateAdvanceIn(@RequestParam("SupplierID") Long sid, @RequestParam("AdvanceIn") Double ain){
        SupplierEntity supplier = supplierService.selectById(sid);

        supplier.setContacts(supplier.getContacts());
        supplier.setType(supplier.getType());
        supplier.setDescription(supplier.getDescription());
        supplier.setEmail(supplier.getEmail());
        supplier.setAdvancein(supplier.getAdvancein() + sid); //增加预收款的金额，可能增加的是负值
        supplier.setBeginneedget(supplier.getBeginneedget());
        supplier.setBeginneedpay(supplier.getBeginneedpay());
        supplier.setIsystem(1);
        supplier.setPhonenum(supplier.getPhonenum());
        supplier.setSupplier(supplier.getSupplier());

        supplier.setFax(supplier.getFax());
        supplier.setTelephone(supplier.getTelephone());
        supplier.setAddress(supplier.getAddress());
        supplier.setTaxnum(supplier.getTaxnum());
        supplier.setBankname(supplier.getBankname());
        supplier.setAccountnumber(supplier.getAccountnumber());
        supplier.setTaxrate(supplier.getTaxrate());

        supplier.setEnabled(supplier.getEnabled());
        supplierService.updateAllColumnById(supplier);

        return R.ok();
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:supplier:info")
    public R info(@PathVariable("id") Long id) {
        SupplierEntity supplier = supplierService.selectById(id);

        return R.ok().put("supplier", supplier);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:supplier:save")
    public R save(@RequestBody SupplierEntity supplier) {
        supplierService.insert(supplier);

        return R.ok();
    }

    @RequestMapping("/checkIsNameExist")
    public R checkIsNameExist(@RequestBody SupplierEntity supplierEntity) {
        List<SupplierEntity> supplier = supplierService.selectList(new EntityWrapper<SupplierEntity>()
                .eq("supplier", supplierEntity.getSupplier())
        );

        if (supplier == null || supplier.size() > 0) {
            return R.ok().put("flag", 1);
        }
        return R.ok().put("flag", 0);
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:supplier:update")
    public R update(@RequestBody SupplierEntity supplier) {
        ValidatorUtils.validateEntity(supplier);
        supplierService.updateAllColumnById(supplier);//全部更新

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:supplier:delete")
    public R delete(@RequestBody Long[] ids) {
        supplierService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }


    @RequestMapping("/batchSetEnable")
    public R batchSetEnable(String ids, boolean enabled) {
        String[] split = ids.split(",");
        for (String str : split) {
            SupplierEntity supplierEntity = new SupplierEntity();
            supplierEntity.setId(Long.valueOf(str));
            supplierEntity.setEnabled(enabled);
            supplierService.updateById(supplierEntity);
        }

        return R.ok();
    }

    @RequestMapping("/exportExcel")
    public String exportExcel(@RequestParam Map<String, Object> params, HttpServletResponse response) {
        try {
            String pageSize = Integer.MAX_VALUE + "";
            String pageNo = "1";
            Object pageSizeObj = params.get("pageSize");
            Object pageNoObj = params.get("pageNo");
            if (pageSizeObj != null) {
                pageSize = pageSizeObj.toString();
            }
            if (pageNoObj != null) {
                pageNo = pageNoObj.toString();
            }
            params.put("limit", pageSize);
            params.put("page", pageNo);

            String type = Tools.dealNullStr(params.get("type"));
            if( "Vendor".equals(type)){
                type = "供应商";
            }
            else if("Customer".equals(type)){
                type = "客户";
            }
            else if("Member".equals(type)){
                type = "会员";
            }
            String fileName = type+"报表" + System.currentTimeMillis() + ".xls";
            Page<SupplierEntity> page = supplierService.selectPage(
                    new Query<SupplierEntity>(params).getPage(),
                    new EntityWrapper<SupplierEntity>()
                            .like("type", type)
            );
            PageUtils pageUtils = new PageUtils(page);
            InputStream inputStream = supplierService.exmportExcel(null, (List<SupplierEntity>) pageUtils.getList());
            response.setContentType("application/x-download");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"), "iso8859-1") );
            OutputStream out = response.getOutputStream();
            IOUtils.copy(inputStream,out);
            out.close();

            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "excel";
    }

    @RequestMapping("/importExcel")
    public void importExcel(MultipartFile supplierFile) {
        //excel表格file
        Boolean result = false;
        String returnStr = "";
        try {
            InputStream in = supplierService.importExcel(supplierFile);
            returnStr = SupplierConstants.BusinessForExcel.EXCEL;
        } catch (Exception e) {
        }
    }

}
